#!/bin/bash

# 配置参数
INSTALL_DIR="/home/remote/project/profile"
SCRIPT_NAME="gpio-export"
CONFIG_FILE="${INSTALL_DIR}/gpio_export.ini"  # 配置文件路径
GPIO_DIR=/sys/class/gpio
LOG_FILE="${INSTALL_DIR}/${SCRIPT_NAME}.log"  # 日志文件

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 确保安装目录存在
mkdir -p "$INSTALL_DIR" || {
    echo "错误：无法创建安装目录 $INSTALL_DIR"
    exit 1
}

# 日志函数（追加到日志文件并输出到控制台）
log() {
    local level="$1"
    local msg="$2"
    local color=$(case "$level" in INFO) echo "$GREEN" ;; WARN) echo "$YELLOW" ;; ERROR) echo "$RED" ;; *) echo "$NC" ;; esac)
    
    # 记录到日志文件
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $level: $msg" >> "$LOG_FILE"
    
    # 输出到控制台
    echo -e "$color$(date '+%Y-%m-%d %H:%M:%S') - $level: $msg$NC"
}

# 从配置文件加载 GPIO（若不存在则初始化）
load_gpio_config() {
    if [ ! -f "$CONFIG_FILE" ]; then
        echo "# GPIO 配置文件" > "$CONFIG_FILE"
        echo "GPIO4_B3=139" >> "$CONFIG_FILE"
        echo "GPIO4_B4=140" >> "$CONFIG_FILE"
        echo "# 添加新 GPIO 格式：名称=编号" >> "$CONFIG_FILE"
        echo -e "${YELLOW}已创建初始配置文件：$CONFIG_FILE${NC}"
    fi
    
    # 读取配置到关联数组
    declare -gA GPIO_MAP=()
    while IFS= read -r line || [ -n "$line" ]; do
        [[ "$line" =~ ^#|^[[:space:]]*$ ]] && continue  # 跳过注释和空行
        
        # 提取名称和编号
        name="${line%%=*}"
        num="${line#*=}"
        
        GPIO_MAP["$name"]="$num"
    done < "$CONFIG_FILE"
    
    if [ ${#GPIO_MAP[@]} -eq 0 ]; then
        log ERROR "配置文件中无有效 GPIO 定义！"
        exit 1
    fi
}

# 导出 GPIO（带权限处理和重试机制）
export_gpio() {
    local gpio_num="$1"
    local gpio_name="$2"  # 用于日志记录
    local gpio_path="$GPIO_DIR/gpio$gpio_num"
    local max_retries=3
    local retry_delay=1
    
    # 检查是否已导出
    [ -d "$gpio_path" ] && {
        log INFO "GPIO$gpio_num ($gpio_name) 已导出"
        return 0
    }
    
    log INFO "尝试导出 GPIO$gpio_num ($gpio_name)..."
    
    for ((i=1; i<=max_retries; i++)); do
        echo "$gpio_num" | sudo tee "$GPIO_DIR/export" >/dev/null
        if [ $? -eq 0 ]; then
            # 等待一小段时间让系统完成导出
            sleep 0.5
            if [ -d "$gpio_path" ]; then
                log INFO "GPIO$gpio_num ($gpio_name) 导出成功"
                return 0
            fi
        fi
        
        log WARN "导出 GPIO$gpio_num ($gpio_name) 失败（尝试 $i/$max_retries），重试中..."
        sleep "$retry_delay"
    done
    
    log ERROR "导出 GPIO$gpio_num ($gpio_name) 失败！权限不足或编号错误"
    return 1
}

# 读取 GPIO 状态
read_status() {
    local gpio_name="$1"
    local gpio_num="${GPIO_MAP[$gpio_name]}"
    [ -z "$gpio_num" ] && { log ERROR "未知 GPIO: $gpio_name"; return 2; }
    
    local gpio_path="$GPIO_DIR/gpio$gpio_num"
    
    if [ -d "$gpio_path" ]; then
        if [ -f "$gpio_path/value" ]; then
            local status=$(cat "$gpio_path/value")
            echo "$status"
            return 0
        else
            log INFO "GPIO$gpio_num ($gpio_name) 已导出，但值文件不存在"
            return 0
        fi
    else
        log INFO "GPIO$gpio_num ($gpio_name) 未导出"
        return 1
    fi
}

# 显示所有 GPIO 状态
show_all_status() {
    echo -e "${YELLOW}==== GPIO 状态汇总 ====${NC}"
    for name in "${!GPIO_MAP[@]}"; do
        local num="${GPIO_MAP[$name]}"
        read_status "$name" >/dev/null
        local status=$?
        
        echo -n "$name ($num): "
        if [ $status -eq 0 ]; then
            echo -e "${GREEN}已导出${NC}"
        elif [ $status -eq 1 ]; then
            echo -e "${RED}未导出${NC}"
        else
            echo -e "${YELLOW}未知${NC}"
        fi
    done
}

# 主逻辑
load_gpio_config

case "$1" in
    export)
        # 导出单个或所有 GPIO
        if [ -z "$2" ]; then
            log ERROR "请指定要导出的 GPIO 名称（如 $SCRIPT_NAME export GPIO4_B3）"
            exit 1
        elif [ "$2" == "all" ]; then
            log INFO "开始导出所有 GPIO..."
            for name in "${!GPIO_MAP[@]}"; do
                export_gpio "${GPIO_MAP[$name]}" "$name"
            done
            log INFO "所有 GPIO 导出完成"
        else
            export_gpio "${GPIO_MAP[$2]}" "$2"
        fi
        ;;
    
    status)
        # 查看单个或所有 GPIO 状态
        if [ -z "$2" ]; then
            show_all_status
        elif [ "$2" == "all" ]; then
            show_all_status
        else
            read_status "$2" >/dev/null
            local exit_code=$?
            [ $exit_code -eq 0 ] && log INFO "$2 状态: ${GREEN}已导出${NC}" || log INFO "$2 状态: ${RED}未导出${NC}"
            exit $exit_code
        fi
        ;;
    
    install)
        # 安装 systemd 服务（首次运行时执行）
        SYSTEMD_SERVICE="[Unit]
Description=GPIO Export Service
After=sysinit.target local-fs.target

[Service]
Type=oneshot
ExecStart=/bin/bash $INSTALL_DIR/${SCRIPT_NAME}.sh export all
RemainAfterExit=yes
TimeoutStartSec=30

[Install]
WantedBy=multi-user.target"
        
        echo "$SYSTEMD_SERVICE" > "/etc/systemd/system/${SCRIPT_NAME}.service"
        systemctl daemon-reload
        systemctl enable --now ${SCRIPT_NAME}.service
        echo -e "${GREEN}服务安装完成！${NC}"
        systemctl status ${SCRIPT_NAME}.service --no-pager
        ;;
    
    *)
        echo -e "用法: $0 [操作] [参数]"
        echo -e "  ${GREEN}操作选项:${NC}"
        echo -e "    install       安装 systemd 服务（首次运行）"
        echo -e "    export <名称> 导出单个 GPIO（如: export GPIO4_B3）"
        echo -e "    export all    导出所有配置的 GPIO"
        echo -e "    status <名称> 查看单个 GPIO 状态"
        echo -e "    status all    查看所有 GPIO 状态"
        echo -e "\n${YELLOW}当前配置的 GPIO:${NC}"
        for name in "${!GPIO_MAP[@]}"; do
            echo "  - $name = ${GPIO_MAP[$name]}"
        done
        exit 1
        ;;
esac